package com.yaozheng.vocationaltraining.fragment.exam;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.TextView;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.db.PaperAnswerCacheDao;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.IMasterQuestionView;
import com.yaozheng.vocationaltraining.iview.IMastersTourView;
import com.yaozheng.vocationaltraining.service.MasterQuestionService;
import com.yaozheng.vocationaltraining.service.MastersTourService;
import com.yaozheng.vocationaltraining.service.impl.MasterQuestionServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.MastersTourServiceImpl;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.ExamProgressStatusView;

import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.List;

/**
 * 大师之旅
 */
@EFragment(R.layout.activity_masters_tour)
public class MastersTourFragment extends BaseFragment implements
        SwipeRefreshLayout.OnRefreshListener, IMastersTourView, IMasterQuestionView,
        View.OnClickListener {
    int i;
    @ViewById
    TextView checkpointsTripText1, checkpointsTripText2, checkpointsTripText3,
            checkpointsTripText4, checkpointsTripText5, checkpointsTripText6,
            checkpointsTripText7, checkpointsTripText8, checkpointsTripText9,
            checkpointsTripText10, checkpointsTripText11,
            checkpointsTripText12;
    @ViewById
    ExamProgressStatusView checkpointsTripProgressStatusView1, checkpointsTripProgressStatusView2, checkpointsTripProgressStatusView3, checkpointsTripProgressStatusView4, checkpointsTripProgressStatusView5, checkpointsTripProgressStatusView6, checkpointsTripProgressStatusView7, checkpointsTripProgressStatusView8, checkpointsTripProgressStatusView9, checkpointsTripProgressStatusView10, checkpointsTripProgressStatusView11, checkpointsTripProgressStatusView12;

    TextView[] checkpointsTripTexts;

    ExamProgressStatusView[] checkpointsTripProgressStatusViews;
    @Bean(MastersTourServiceImpl.class)
    MastersTourService mastersTourService;
    @Bean(MasterQuestionServiceImpl.class)
    MasterQuestionService masterQuestionService;

    /**
     * 下拉刷新
     */
    @ViewById
    SwipeRefreshLayout swipeRefreshLayout;

    @ViewById
    TextView headTitleText;

    JSONObject masterJsonObject;

    int step;

    PaperAnswerCacheDao paperAnswerCacheDao;

    private String examTitle;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    @AfterViews
    public void initView() {
        i = getBaseActivity().getIntentInt("i");

        String title = "";
        if (i == 1) {
            title = getString(R.string.imageMasterStr);// "形象大师";
        }
        if (i == 2) {
            title = getString(R.string.maintenanceMasterStr);// "维保大师";
        } else if (i == 3) {
            title = getString(R.string.serviceMasterStr);// "服务大师";
        } else if (i == 4) {
            title = getString(R.string.salesMasterStr);//  "销售大师";
        } else if (i == 5) {
            title = getString(R.string.goodsMasterStr);
        } else if (i == 6) {
            title = getString(R.string.brandMasterStr);
        } else if (i == 7) {
            title = getString(R.string.goodsMasterStr5);
        }
        headTitleText.setText(title);
        checkpointsTripTexts = new TextView[]{checkpointsTripText1,
                checkpointsTripText2, checkpointsTripText3,
                checkpointsTripText4, checkpointsTripText5,
                checkpointsTripText6, checkpointsTripText7,
                checkpointsTripText8, checkpointsTripText9,
                checkpointsTripText10, checkpointsTripText11,
                checkpointsTripText12};

        checkpointsTripProgressStatusViews = new ExamProgressStatusView[]{
                checkpointsTripProgressStatusView1,
                checkpointsTripProgressStatusView2, checkpointsTripProgressStatusView3,
                checkpointsTripProgressStatusView4, checkpointsTripProgressStatusView5,
                checkpointsTripProgressStatusView6, checkpointsTripProgressStatusView7,
                checkpointsTripProgressStatusView8, checkpointsTripProgressStatusView9,
                checkpointsTripProgressStatusView10, checkpointsTripProgressStatusView11,
                checkpointsTripProgressStatusView12
        };

        for (int i = 0; i < checkpointsTripTexts.length; i++) {
            TextView textView = checkpointsTripTexts[i];
            textView.setOnClickListener(this);
            textView.setTag(i);
            textView.setTag(R.id.tag_title, textView.getText().toString());
            ExamProgressStatusView checkpointsTripProgressStatusView = checkpointsTripProgressStatusViews[i];
            checkpointsTripProgressStatusView.setOnClickListener(this);
            checkpointsTripProgressStatusView.setTag(i);
            checkpointsTripProgressStatusView.setTag(R.id.tag_title, textView.getText().toString());

        }
        paperAnswerCacheDao = new PaperAnswerCacheDao(getBaseActivity());
        // try {
        // checkpointsTripTitleImage
        // .setImageResource(R.drawable.image_master_title_image1
        // + (i - 1));
        // } catch (Exception e) {
        // checkpointsTripTitleImage
        // .setImageResource(R.drawable.image_master_title_image1);
        // }

        mastersTourService.init(this);
        masterQuestionService.init(this);
        swipeRefreshLayout.setOnRefreshListener(this);
        updateData();
        // i = 7 - i;
//        swipeRefreshLayout.postDelayed(new Runnable() {
//
//            @Override
//            public void run() {
//                if (isResponseResult()) {
//                    swipeRefreshLayout.setRefreshing(true);
//                    onRefresh();
//                }
//            }
//        }, 500);
        onRefresh();
    }

    public void loadData() {
        mastersTourService.checkpointsProgress(i);
    }

//	/**
//	 * 进入考试页面
//	 */
//	public void enterExamPage(View view) {
//		Intent intent = new Intent();
//		intent.setClassName(this, Constants.ONLINE_EXAM_ACTIVITY_CLASS_NAME);
//		startActivity(intent);
//	}

    @Override
    public void onRefresh() {
        loadData();

    }


    @UiThread
    @Override
    public void getQuestionListSuccess(JSONObject jsonObject) {
        cancelOperatingProgressDialog();
        JSONObject paperJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "paper");
        // 进入考试
        Intent intent = getBaseActivity().getIntent();
        intent.putExtra("examType", String.valueOf(6 + i));
        intent.putExtra("paperId",
                TypeUtils.getJsonInteger(paperJsonObject, "id"));
        intent.putExtra("startTimeLong", System.currentTimeMillis());
        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
        intent.putExtra("examTitle", examTitle);
        getHomeActivity().openOnlineExamFragment();
    }

    @UiThread
    @Override
    public void getQuestionListError(String error) {
        cancelOperatingProgressDialog();
        alertMessage(error);
    }

    /**
     * 刷新数据
     */
    public void updateData() {
        if (masterJsonObject != null) {
            step = TypeUtils.getJsonInteger(masterJsonObject, "step");
        } else {
            step = -1;
        }
        for (int i = 0; i < checkpointsTripProgressStatusViews.length; i++) {
            ExamProgressStatusView examProgressStatusView = checkpointsTripProgressStatusViews[i];
            TextView checkpointsTripText = checkpointsTripTexts[i];
            if (i < step) {
                examProgressStatusView.enable();
                checkpointsTripText.setTextColor(getResources().getColor(R.color.default_font_color));
                //考完
                examProgressStatusView.setStatus(-3);
            } else if (i > step) {
                examProgressStatusView.disable();
                //未考
                examProgressStatusView.setStatus(-1);
                checkpointsTripText.setTextColor(getResources().getColor(R.color.disable_font_color));

            } else {
                examProgressStatusView.enable();
                //考试中
                examProgressStatusView.setStatus(-2);
                checkpointsTripText.setTextColor(getResources().getColor(R.color.default_font_color));

            }
        }
    }


    @Override
    public void cancelLoadDataProgressDialog() {
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        if (tag instanceof Integer) {
            int indexTag = (Integer) v.getTag();
            examTitle = (String) v.getTag(R.id.tag_title);
            if (masterJsonObject != null) {
                if (indexTag == step) {

                    String localDataQuestions;
                    List<String> returnData = paperAnswerCacheDao.findQuestionsByStatus(6 + i);
                    long endTime = 0;
                    if (returnData == null || returnData.size() < 1) {
                        localDataQuestions = null;
                    } else {
                        localDataQuestions = returnData.get(0);
                        try {
                            endTime = Long.parseLong(returnData.get(1));
                        } catch (Exception ex) {
                            localDataQuestions = null;
                        }
                    }
                    if (localDataQuestions == null) {
                        showOperatingProgressDialog("取题中...");
                        // 考试
                        masterQuestionService.getQuestionList(
                                TypeUtils.getJsonInteger(masterJsonObject, "id"),
                                step + 1);
                    } else {

                        JSONObject paperJsonObject = JsonUtils.getJsonObject(localDataQuestions);
                        // 进入考试
                        Intent intent = getBaseActivity().getIntent();
                        intent.putExtra("examType", String.valueOf(i + 6));
                        intent.putExtra("paperId",
                                TypeUtils.getJsonInteger(paperJsonObject, "id"));
                        //可以算出结束时间
                        long benginTime = System.currentTimeMillis();
                        paperJsonObject.put("duration", (endTime - benginTime) / 1000);
                        intent.putExtra("startTimeLong", System.currentTimeMillis());
                        intent.putExtra("paperJsonObjectStr", paperJsonObject.toString());
                        intent.putExtra("examTitle", examTitle);

                        getHomeActivity().openOnlineExamFragment();
                    }
                }
            }
        }
    }


    public void enterExamPageClick() {

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.ONLINE_EXAM_RESULT_CODE
                && resultCode == Constants.ONLINE_EXAM_CARRY_OUT_AN_ASSIGNMENT_REQUEST_CODE) {
            swipeRefreshLayout.setRefreshing(true);
            onRefresh();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @UiThread
    @Override
    public void checkpointsProgressSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        masterJsonObject = TypeUtils
                .getJsonObject(jsonObject, "data", "master");
        updateData();
    }

    @UiThread
    @Override
    public void checkpointsProgressError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    @Override
    public void onDestroyView() {
        step = -1;
        masterJsonObject = null;
        super.onDestroyView();
    }
}
